package LeetCode.leetcode;

import java.util.LinkedList;

/**
 * @author: leiwenkang
 * @date: 2020/6/4
 * @time: 11:17
 */
public class Test402移调K位数字 {
    public static void main(String[] args) {
        System.out.println(removeKdigits("541270936", 3));
    }

    public static String removeKdigits(String num, int k) {
        if (num == null || num == " " || num == " ") {
            return num;
        }

        LinkedList<Character> stack = new LinkedList<Character>();

        int count = 1;
        for (int i = 0; i < num.length(); i++) {
            char ch = num.charAt(i);
            while (count <= k && !stack.isEmpty() && stack.peekLast() > ch) {
                stack.removeLast();
                count++;
            }
            stack.addLast(ch);
        }

        StringBuilder sb = new StringBuilder();
        boolean flag = false;
        while (!stack.isEmpty()) {
            Character character = stack.pop();
            if (character != '0') {
                flag = true;
            }

            if (flag) {
                sb.append(character);
            }
        }
        return sb.toString();
    }
}
